package fr.bugtracker.bean.security;

import java.io.IOException;
import java.net.HttpURLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import fr.bugtracker.commun.outils.UtilsMetier;

/**
 * @author Laurent
 * @version 0.1
 */
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

	/**
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException authenticationException) throws IOException, ServletException {
		if (authenticationException instanceof BadCredentialsException) {
			httpServletResponse.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, UtilsMetier.getMessage("fonctionnel.compte.erreur.mauvais_login_password"));
		}
		if (authenticationException instanceof CredentialsExpiredException) {
			httpServletResponse.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, UtilsMetier.getMessage("fonctionnel.compte.erreur.password_expire"));
		}
		if (authenticationException instanceof AccountExpiredException) {
			httpServletResponse.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, UtilsMetier.getMessage("fonctionnel.compte.erreur.expire"));
		}
		if (authenticationException instanceof LockedException) {
			httpServletResponse.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, UtilsMetier.getMessage("fonctionnel.compte.erreur.bloque"));
		}
		if (authenticationException instanceof DisabledException) {
			httpServletResponse.sendError(HttpURLConnection.HTTP_UNAUTHORIZED, UtilsMetier.getMessage("fonctionnel.compte.erreur.desactive"));
		}
	}
}
